package com.sctvcloud.renhe.ui.activities;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Pair;
import android.view.View;
import android.widget.TextView;

import com.bupt.library.picturegallery.PictureGalleryView;
import com.githang.statusbar.StatusBarCompat;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.ShareFragment;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.sctvcloud.renhe.R;
import com.sctvcloud.renhe.application.Cache;
import com.sctvcloud.renhe.application.Constances;
import com.sctvcloud.renhe.base.BaseDetailActivity;
import com.sctvcloud.renhe.beans.AttitudesBean;
import com.sctvcloud.renhe.beans.FCollect;
import com.sctvcloud.renhe.beans.FComment;
import com.sctvcloud.renhe.beans.FUsers;
import com.sctvcloud.renhe.beans.Gallery;
import com.sctvcloud.renhe.beans.GalleyImgBean;
import com.sctvcloud.renhe.beans.SingleResult;
import com.sctvcloud.renhe.http.AbsNetCallBack;
import com.sctvcloud.renhe.http.NetUtils;
import com.sctvcloud.renhe.http.ParamsEditor;
import com.sctvcloud.renhe.ui.utils.CollectionUtils;
import com.sctvcloud.renhe.ui.utils.SkipUtil;
import com.sctvcloud.renhe.utils.UserManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 图集
 */
public class GalleryActivity extends BaseDetailActivity {

    @BindView(R.id.gallery_view)
    PictureGalleryView mPictureGalleryView;
    public final static String EXTRA_URL = "url";
    private Gallery item;
    ArrayList<String> imageList = new ArrayList<>();
    ArrayList<String> describeList = new ArrayList<>();
    private int types = Constances.COMMENT_TYPE_NEWS;

    ArrayList<Pair<String, String>> pairs;

    private boolean isCollected = false;
    private FCollect mFCollect;

    private int commentNumber;
    private AttitudesBean attitudes;
    private int typeName = 6;//新闻类型  4视频新闻  5音频新闻 6图文新闻
    private int indexNumber = 0;
    private int capacity = 5;//请求数据条数
    public static int REQUEST_COMMENT_CODE = 505;
    String news_url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ArrayList<String> imageList = new ArrayList<>();
        mPictureGalleryView.setOnSwipeOffListener(new PictureGalleryView.OnSwipeOffListener() {
            @Override
            public void onSwipeRight() {
                finish();
            }

            @Override
            public void onSwipeLeft() {

            }
        });

        if(!TextUtils.isEmpty(getIntent().getStringExtra(EXTRA_URL))){
            news_url = getIntent().getStringExtra(EXTRA_URL);
            getPicList(news_url);
        }

        mPictureGalleryView.setImageClickListener(newsItemClick);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.black));

    }



    public void getPicList(String url) {
        if (TextUtils.isEmpty(url)) {
            toast("数据错误");
            JLog.e("int " + this.getClass().getSimpleName() + " url wrong ::" + url);
            return;
        }

        NetUtils.getNetAdapter().getGallery(getOwnerName(), url, new AbsNetCallBack<Gallery>(Gallery.class) {

            @Override
            public void onSuc(Gallery datas) {
                item = datas;
                if(datas.getImages()!= null && datas.getImages().size()>0){
                    for(GalleyImgBean item : datas.getImages()){
                        imageList.add(UrlUtils.linkUrls(Constances.ST_BASE_URL, item.getImageUrl()));
                        describeList.add(item.getImageDescription());
                    }

                    mPictureGalleryView.updateData(datas.getNewsTitle(), imageList, describeList, null);

                }

                initCollectData();
                getAttitudes(item.getNewsId());
                getCommentNews(item.getNewsId(), Constances.REQUEST_COMMENT_TYPE_NEWS, capacity, indexNumber);

            }

            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
            }

            @Override
            public void onEnd() {
                super.onEnd();

            }
        });



    }


    @Override
    protected void onCommentSendSuc(int mode) {
        super.onCommentSendSuc(mode);
        getCommentNews(item.getNewsId(), Constances.REQUEST_COMMENT_TYPE_NEWS, capacity, indexNumber);

    }


    @Override
    protected void onCommentGetListSuc(int count, List<FComment> fProgrammes) {
        if (indexNumber >= count || count <= capacity) {
            commentNumber = count;
            refreshBottomCommentShowing(count);
        //    refreshCommentShowing(fProgrammes);
        } else {
            requestAll(count);
        }

    }


    /**
     * 获取全部数据
     *
     * @param ca
     */
    private void requestAll(int ca) {
        capacity = ca;
        indexNumber = 0;
        getCommentNews(item.getNewsId(), Constances.REQUEST_COMMENT_TYPE_NEWS, capacity, indexNumber);
    }


    private void refreshBottomCommentShowing(int count) {
//        String str = getString(R.string.detail_comment_no);
        String str = "0";
        //  if (commentColumn != null && count > 0) {
        if (count > 0) {
            if (count > 99) {
                str = getString(R.string.detail_comment_counts);
            } else {
                str = getString(R.string.detail_comment_count, count);
            }
        }
        mPictureGalleryView.getCommentView().setText(str);
    }


    PictureGalleryView.ImageClickListener newsItemClick = new PictureGalleryView.ImageClickListener() {
        @Override
        public void onItemInternalClick( View view) {
            pairs = new ArrayList<>();
            switch (view.getId()) {
                case R.id.iv_close:
                    finish();
                    break;

                case R.id.comment_layout_write_comment:
                    String newid = item.getNewsId();
                    showCommentDialog(newid, null, types);  //0代表新闻评论
                    pairs.add(new Pair<>("行为类型", "评论"));
                    break;
                case R.id.comment_layout_number:
                    if (commentNumber != 0) {
                        Intent intent = new Intent(GalleryActivity.this, CommentActivity.class);
                        String id = item.getNewsId();
                        intent.putExtra(EX_ID, id);
                        intent.putExtra(EX_TYPE_NEWS, Constances.REQUEST_COMMENT_TYPE_NEWS);
                        intent.putExtra(EX_COMMENT_TYPE, types);
                        startActivityForResult(intent, REQUEST_COMMENT_CODE);
                        pairs.add(new Pair<>("行为类型", "评论"));
                    }
                    break;
                case R.id.comment_layout_doup:
                    newsDoUp();
                    break;
                case R.id.comment_layout_collection:
                    if (isCollected) {
                        pairs.add(new Pair<>("行为类型", "取消收藏"));
                    } else {
                        pairs.add(new Pair<>("行为类型", "收藏"));
                    }
                    doCollect();
                    if (null != item) {
                        GridsumWebDissector.getInstance().trackEvent(GalleryActivity.this, "", item.getNewsTitle(), "", 200, pairs);
                    }
                    break;
                case R.id.comment_layout_share:
                    if (!TextUtils.isEmpty(item.getNewsSharedUrl())) {
                        setNewsId(item.getNewsId());
                        showShareFragment(item, new ShareFragment.OnShareFragmentClickListener() {
                            @Override
                            public void onClick(Pair<String, String> pair) {
                                pairs = new ArrayList<>();
                                pairs.add(pair);
                                GridsumWebDissector.getInstance().trackEvent(GalleryActivity.this, "", item.getNewsTitle(), "", 200, pairs);
                            }
                        });
                    } else {
                        toast(R.string.share_data_wrong);
                    }
                    break;
                default:
                    break;
            }


        }
    };


    private void doCollect() {
        if (isCollected) {
            CollectionUtils.getInstance().removeCollection(mFCollect.getId());
            setBtnCollectStyle(false);
            toast(R.string.mine_collection_removed_toast);
        } else {
            CollectionUtils.getInstance().addCollection(mFCollect);
            setBtnCollectStyle(true);
            toast(R.string.mine_collection_succ_toast);
        }
    }

    private void setBtnCollectStyle(boolean isCollected) {
        this.isCollected = isCollected;
        Drawable drawable = GalleryActivity.this.getResources().getDrawable(isCollected ? R.mipmap.icon_collections_on : R.mipmap.icon_collection);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        setDrawables(mPictureGalleryView.getCollectView(),drawable, null, null, null);
    }


    private boolean initCollectData() {
        if (item == null) {
            return false;
        }
        if (mFCollect == null) {
            mFCollect = new FCollect();
            mFCollect.setId(item.getNewsId());
            String url = item.getNewsSharedUrl();
            mFCollect.setUrl(TextUtils.isEmpty(url) ? baseUrl : url);
            mFCollect.setTitle(item.getNewsTitle());
            String[] imgs = splitImgs(item.getNewsImage());
            mFCollect.setImg(imgs[0]);
            mFCollect.setTime(item.getPubTime());
            mFCollect.setDataType(item.getNewsType());
        //    mFCollect.setNewsMediaLength(fNews.getNewsMediaLength());
            mFCollect.setLable(item.getLable());
            mFCollect.setSub_news_url(news_url);
        }

        isCollected = CollectionUtils.getInstance().isCollected(mFCollect.getId());
        setBtnCollectStyle(isCollected);


        return true;
    }


    private String[] splitImgs(String org){
        return org.split(",");
    }


    /**
     * 新闻点赞
     */
    private void newsDoUp() {
        final String newId = item.getNewsId();
        if (UserManager.isLoginS()) {

            setDrawableEnlarge();
            ParamsEditor pe = new ParamsEditor();
//        HashMap<String, Object> param = new HashMap<>();
            pe.put("dynamicId", newId);
            pe.put("fType", 3);//1 主播 2报料 3新闻 4 直播 5视频
//        pe.put("token", UserManager.getInstance().getToken());
            pe.put("userId", UserManager.getInstance().getUser().getUserId());

            NetUtils.getNetAdapter().doUpForDynamics(getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsNetCallBack<SingleResult>(SingleResult.class) {
                @Override
                public void onSuc(SingleResult singleResult) {
                    if (singleResult.isSuccess()) {
                        SkipUtil.skipToAddUserOperate(GalleryActivity.this, getOwnerName(), 13, typeName, "新闻详情点赞/取消点赞", newId, Cache.getInstance().getCurrentChannelId());
                        if (null != attitudes) {
                            if (attitudes.isDigg()) {
                                attitudes.setDigg(!attitudes.isDigg());
                                attitudes.setAttitudesCount(attitudes.getAttitudesCount() - 1);
                            } else {
                                attitudes.setDigg(!attitudes.isDigg());
                                attitudes.setAttitudesCount(attitudes.getAttitudesCount() + 1);
                            }

                            if (attitudes.isDigg()) {
                                Drawable drawable = GalleryActivity.this.getResources().getDrawable(R.mipmap.all_icon_dianzan_on);
                                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                setDrawables(mPictureGalleryView.getDoUpView(),drawable, null, null, null);
                                mPictureGalleryView.getDoUpView().setTextColor(GalleryActivity.this.getResources().getColor(R.color.color_989898));
                            } else {
                                Drawable drawable = GalleryActivity.this.getResources().getDrawable(R.mipmap.all_icon_dianzan_off);
                                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                setDrawables(mPictureGalleryView.getDoUpView(),drawable, null, null, null);
                                mPictureGalleryView.getDoUpView().setTextColor(GalleryActivity.this.getResources().getColor(R.color.color_989898));
                            }
                            if(attitudes.getAttitudesCount()>0) {
                                mPictureGalleryView.getDoUpView().setText("" + attitudes.getAttitudesCount());
                            }else{
                                mPictureGalleryView.getDoUpView().setText("0" );
                            }

                            if (attitudes.isDigg()) {
                                addInvitation(Constances.ADD_INTEGRAL_DOUP, false);
                            }
                        }

                    }
                }

                @Override
                public void onError(Throwable ex, String errorMsg, int netCode) {
                    super.onError(ex, errorMsg, netCode);
                }
            });

        } else {
            toLogin();
        }
    }


    /**
     * 获取新闻点赞
     */
    private void getAttitudes(final String newsId) {
        ParamsEditor pe = new ParamsEditor();
//        HashMap<String, Object> param = new HashMap<>();
        pe.put("dynamicId", newsId);
        pe.put("fType", 3);//1 主播 2报料 3新闻(短视频) 4 直播
//        pe.put("token", UserManager.getInstance().getToken());
        FUsers user = UserManager.getInstance().getUser();
        if (user != null && !TextUtils.isEmpty(user.getUserId())) {
            pe.put("userId", user.getUserId());
        } else {
            pe.put("userId", "");
        }
        NetUtils.getNetAdapter().getAttitudes(getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsNetCallBack<AttitudesBean>(AttitudesBean.class) {
            @Override
            public void onSuc(AttitudesBean attitudesBean) {
                if (null != attitudesBean) {
                    attitudes = attitudesBean;
                    if (attitudesBean.isDigg()) {
                        Drawable drawable = GalleryActivity.this.getResources().getDrawable(R.mipmap.all_icon_dianzan_on);
                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                        setDrawables(mPictureGalleryView.getDoUpView(),drawable, null, null, null);
                        mPictureGalleryView.getDoUpView().setTextColor(GalleryActivity.this.getResources().getColor(R.color.color_989898));
                    } else {
                        Drawable drawable = GalleryActivity.this.getResources().getDrawable(R.mipmap.all_icon_dianzan_off);
                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                        setDrawables(mPictureGalleryView.getDoUpView(),drawable, null, null, null);
                        mPictureGalleryView.getDoUpView().setTextColor(GalleryActivity.this.getResources().getColor(R.color.color_989898));
                    }
                    if(attitudesBean.getAttitudesCount()>0) {
                        mPictureGalleryView.getDoUpView().setText("" + attitudesBean.getAttitudesCount());
                    }else{
                        mPictureGalleryView.getDoUpView().setText("0" );
                    }
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
            }
        });
    }
    
    
    
    

    private boolean isSetNewDrawable = false;
    private Handler handler = new Handler();

    /**
     * 调用使drawable图标渐进变大
     */
    public void setDrawableEnlarge() {
        final Drawable[] dr = mPictureGalleryView.getDoUpView().getCompoundDrawables();
        if (dr.length > 0) {
            isSetNewDrawable = false;
            final Drawable drawable = dr[0];
            if (null != drawable) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        drawable.setBounds(0, 0, drawable.getMinimumWidth() * 9 / 8, drawable.getMinimumHeight() * 9 / 8);
                        setThisDrawable(mPictureGalleryView.getDoUpView(),drawable);
                    }
                }, 10);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        drawable.setBounds(0, 0, drawable.getMinimumWidth() * 8 / 7, drawable.getMinimumHeight() * 8 / 7);
                        setThisDrawable(mPictureGalleryView.getDoUpView(),drawable);
                    }
                }, 20);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        drawable.setBounds(0, 0, drawable.getMinimumWidth() * 7 / 6, drawable.getMinimumHeight() * 7 / 6);
                        setThisDrawable(mPictureGalleryView.getDoUpView(),drawable);
                    }
                }, 30);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        drawable.setBounds(0, 0, drawable.getMinimumWidth() * 6 / 5, drawable.getMinimumHeight() * 6 / 5);
                        setThisDrawable(mPictureGalleryView.getDoUpView(),drawable);
                    }
                }, 45);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        drawable.setBounds(0, 0, drawable.getMinimumWidth() * 5 / 4, drawable.getMinimumHeight() * 5 / 4);
                        setThisDrawable(mPictureGalleryView.getDoUpView(),drawable);
                    }
                }, 65);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        drawable.setBounds(0, 0, drawable.getMinimumWidth() * 4 / 3, drawable.getMinimumHeight() * 4 / 3);
                        setThisDrawable(mPictureGalleryView.getDoUpView(),drawable);
                    }
                }, 80);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        drawable.setBounds(0, 0, drawable.getMinimumWidth() * 6 / 5, drawable.getMinimumHeight() * 6 / 5);
                        setThisDrawable(mPictureGalleryView.getDoUpView(),drawable);
                    }
                }, 90);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        drawable.setBounds(0, 0, drawable.getMinimumWidth() * 5 / 4, drawable.getMinimumHeight() * 5 / 4);
                        setThisDrawable(mPictureGalleryView.getDoUpView(),drawable);
                    }
                }, 100);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        drawable.setBounds(0, 0, drawable.getMinimumWidth() * 8 / 7, drawable.getMinimumHeight() * 8 / 7);
                        setThisDrawable(mPictureGalleryView.getDoUpView(),drawable);
                    }
                }, 110);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                        setThisDrawable(mPictureGalleryView.getDoUpView(),drawable);
                    }
                }, 120);
            }
        }
    }


    /**
     * 设置drawable
     */
    public void setDrawables(TextView v,Drawable left, Drawable top,
                             Drawable right, Drawable bottom) {
        if (null != left) {
            left.setBounds(0, 0, left.getMinimumWidth(), left.getMinimumHeight());
            v.setCompoundDrawables(left, null, null, null);
            isSetNewDrawable = true;
        }
    }

    private void setThisDrawable(TextView v,Drawable drawable) {
        if (null != drawable && !isSetNewDrawable) {
            v.setCompoundDrawables(drawable, null, null, null);
        }
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_gallery);
        ButterKnife.bind(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_COMMENT_CODE) {
             getCommentNews(item.getNewsId(), Constances.REQUEST_COMMENT_TYPE_NEWS, capacity, indexNumber);

        }
    }

}
